package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleCollectionMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleCollectionService;
import com.heima.common.constants.ApArticleCollectionConstants;
import com.heima.common.constants.RedisKeyConstants;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.ApThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Transactional
@Service
public class ApArticleCollectionServiceImpl extends ServiceImpl<ApArticleCollectionMapper, ApArticleCollection> implements ApArticleCollectionService {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 是否收藏
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {

        //0.条件判断
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "缺少文章id");
        }
        //1.从线程中拿到当前用户id
        Integer apUserId = ApThreadLocalUtils.getUser().getId();
        //2.根据用户id和文章id拿取数据
        //2.1判断文章id是否存在
        ApArticle apArticle = apArticleMapper.selectById(dto.getArticleId());
        if (apArticle==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章id不存在");
        }
        LambdaQueryWrapper<ApArticleCollection> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApArticleCollection::getArticleId, dto.getArticleId());
        lambdaQueryWrapper.eq(ApArticleCollection::getUserId, apUserId);
        ApArticleCollection apArticleCollection = getOne(lambdaQueryWrapper);
        //2.1如果有对应的数据则判断是否已经收藏
        if (apArticleCollection != null) {
            //2.1.1如果已经收藏，判断前端传入的参数是否已经收藏
            if (apArticleCollection.getOperation().equals(ApArticleCollectionConstants.IS_COLLECTION)
                    && dto.getOperation().equals(ApArticleCollectionConstants.IS_COLLECTION)) {
                //2.1.1.1如果前端是收藏，则返回提示信息
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已经收藏");
            }
            //2.1.2如果数据库中是取消收藏，判断前端传入的参数是否已经收藏
            if (apArticleCollection.getOperation().equals(ApArticleCollectionConstants.IS_NOT_COLLECTION)
                    && dto.getOperation().equals(ApArticleCollectionConstants.IS_NOT_COLLECTION)) {
                //2.1.2.1如果前端是取消收藏，则返回提示信息
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已经取消收藏");
            }
            //2.3补全参数
            TypeAndPublishedTime(apArticleCollection,dto);
            updateById(apArticleCollection);
        } else {
            //2.2如果没有对应的数据则根据前端参数进行收藏（或取消收藏）
            apArticleCollection = new ApArticleCollection();
            apArticleCollection.setUserId(apUserId);
            apArticleCollection.setArticleId(dto.getArticleId());
            //2.3补全参数
            TypeAndPublishedTime(apArticleCollection,dto);
            save(apArticleCollection);
        }
        //3.保存在redis中
        //3.1设置redisKey
        String redisKey = RedisKeyConstants.COLLECTION_REDIS_KEY_PREFIX + dto.getArticleId();
        //3.2判断是否是收藏
        if (dto.getOperation().equals(ApArticleCollectionConstants.IS_COLLECTION)){
            //3.2.1收藏则保存在redis中
            redisTemplate.opsForHash().put(redisKey, apUserId.toString(), dto.getOperation().toString());
            redisTemplate.opsForHash().increment(redisKey,RedisKeyConstants.COLLECTION_HASH_KEY_COUNT,RedisKeyConstants.COLLECTION_HASH_VALUE_INCREMENT);
        } else {
            //3.2.1取消收藏则删除redis中的数据
            redisTemplate.opsForHash().delete(redisKey,apUserId.toString());
            redisTemplate.opsForHash().increment(redisKey,RedisKeyConstants.COLLECTION_HASH_KEY_COUNT,-RedisKeyConstants.COLLECTION_HASH_VALUE_INCREMENT);
        }

        return ResponseResult.okResult(apArticleCollection);
    }

    //2.3补全参数
    private void TypeAndPublishedTime(ApArticleCollection apArticleCollection,CollectionBehaviorDto dto) {
        //2.3.1收藏参数
        apArticleCollection.setOperation(dto.getOperation());
        //2.3.2时间参数
        apArticleCollection.setPublishedTime(new Date());
        //2.3.3收藏类型（默认是文章）
        if (apArticleCollection.getType() == null) {
            apArticleCollection.setType(ApArticleCollectionConstants.IS_ARTICLE);
        }
    }
}
